package Avocado.util {
	import com.greensock.TweenMax;
	
	import fl.transitions.Tween;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Point;
	import flash.geom.Vector3D;

	public class MouseTilt {
		
		public var target:MovieClip;
		
		public function MouseTilt(target:MovieClip, tiltness:Number) {
			var isInMove:Boolean = false;
			
			target.transform.perspectiveProjection = new PerspectiveProjection;
			target.transform.perspectiveProjection.projectionCenter = new Point(target.stage.stageWidth/2,target.stage.stageWidth/2);
			/*			
			var a:Sprite = new Sprite;
			a.graphics.beginFill(0xffaaff, .33);
			a.graphics.drawCircle(0,0,10);
			a.graphics.endFill();
			a.x = target.transform.perspectiveProjection.projectionCenter.x;
			a.y = target.transform.perspectiveProjection.projectionCenter.y;
			target.stage.addChild(a);
			*/
			
			target.addEventListener(Event.REMOVED_FROM_STAGE, removeTarget);
			target.addEventListener(MouseEvent.MOUSE_OVER, mouseOverTarget);
			target.addEventListener(MouseEvent.MOUSE_MOVE, moveMoveTarget);
			target.addEventListener(MouseEvent.MOUSE_OUT, outTarget);
			target.stage.addEventListener(Event.RESIZE, resizeStage);
			
			function removeTarget(e:Event):void{
				target.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverTarget);
				target.removeEventListener(MouseEvent.MOUSE_MOVE, moveMoveTarget);
				target.removeEventListener(MouseEvent.MOUSE_OUT, outTarget);
				target.stage.removeEventListener(Event.RESIZE, resizeStage);
				target.removeEventListener(Event.REMOVED_FROM_STAGE, removeTarget);
			}
			
			function mouseOverTarget(e:MouseEvent):void{
				TweenMax.to(target, .7, {rotatioY: -((e.localX-50)/50) * tiltness, rotatioX: ((e.localY-50)/50) * tiltness});
			}
			
			function moveMoveTarget(e:MouseEvent):void{
				isInMove = true;
				target.rotationY = -((e.localX-50)/50) * tiltness;
				target.rotationX = ((e.localY-50)/50) * tiltness;
			}
			
			function outTarget(e:MouseEvent):void{
				isInMove = false;
				TweenMax.to(target, tiltness/10, {onComplete: outTargetComplete});	
			}
			
			function outTargetComplete():void{
				if (isInMove == false) {
					TweenMax.to(target, tiltness/20, {rotationY: 0, rotationX: 0});
				}
			}

			function resizeStage(e:Event):void{
				target.transform.perspectiveProjection.projectionCenter = new Point(target.stage.stageWidth/2,target.stage.stageWidth/2);
			}

		}
		
		public static function tilt(target:MovieClip, tiltness:Number):MouseTilt{
			return new MouseTilt(target, tiltness);
		}
	}
}